"""
project: apiAutoTestWeb
file: auth.py
author: zy7y
date: 2021/4/17
desc: 鉴权处理
"""
from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordRequestForm

import core
from db import models

auth = APIRouter(tags=["登录相关"])


# @auth.post("/login")
# async def login(form_data: OAuth2PasswordRequestForm = Depends()):
#     user_obj = await models.User.get(username=form_data.username)
#     if user_obj and core.verify_password(form_data.password, user_obj.password):
#         # return core.Success(data=core.Token(access_token=core.create_access_token({"sub": user_obj.username})))
#         return {"token_type": "bearer", "access_token": core.create_access_token({"sub": user_obj.username})}
#     return core.Fail()

@auth.post("/login")
async def login(user: core.Login):
    try:
        user_obj = await models.User.get(username=user.username)
    except Exception as e:
        return core.Fail(message="用户名或密码错误")
    if user_obj and core.verify_password(user.password, user_obj.password):
        return core.Success(data=core.Token(token=core.create_access_token({"sub": user_obj.username})))
    return core.Fail(message="用户名或密码错误")


@auth.post("/logout")
async def logout(token: str = Depends(core.get_current_user)):
    return core.Success(data=token)
